<template>
  <div class="line-chart-container">
    <div ref="chartRef" :style="{ width: width, height: height }"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'LineChart',
  props: {

    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    xAxisData: {
      type: Array,
      default: () => ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
    },
    seriesData: {
      type: Array,
      default: () => [

      ]
    }
  },
  data() {
    return {
      chartInstance: null
    };
  },
  mounted() {

    this.initChart();
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
    window.removeEventListener('resize', this.handleResize);
  },
  watch: {
    // xAxisData: {
    //   handler() {
    //     this.updateChart();
    //   },
    //   deep: true
    // },
    seriesData: {
      handler() {
        this.updateChart();
      },
      deep: true
    }
  },
  methods: {
    initChart() {
      this.$nextTick(() => {
        this.chartInstance = echarts.init(this.$refs.chartRef);
        this.updateChart();

        // 监听窗口大小变化
        window.addEventListener('resize', this.handleResize);
      });
    },
    updateChart() {
      if (!this.chartInstance) return;
      // 检查数据是否为空或无效
      if (
        !this.seriesData ||
        !Array.isArray(this.seriesData) ||
        this.seriesData.length === 0 ||
        !this.xAxisData ||
        !Array.isArray(this.xAxisData) ||
        this.xAxisData.length === 0
      ) {
        // 可以选择清空图表或直接 return
        this.chartInstance.clear();
        return;
      }

      const option = {
        title: {
          text: this.title,
          left: 'center',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#333'
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          borderColor: '#333',
          textStyle: {
            color: '#fff'
          },
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          icon: 'circle',
          data: this.seriesData.map(item => item.name),
          itemHeight: 10,
          itemWidth: 10,
          itemGap: 30,
          top: 0,
          left: "center"
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: this.xAxisData.length > 7 ? '15%' : '8%',
          top: '15%',
          containLabel: true
        },
        dataZoom: this.xAxisData.length > 7 ? [{
          type: 'slider',

          xAxisIndex: [0],
          height: 10,//组件高度
          bottom: 0,//右边的距离

          // end: Math.min(100, (10 / this.xAxisData.length) * 100), // 固定显示15个数据点
          handleSize: 0,//滑动条的 左右2个滑动条的大小
          handleStyle: {
            color: '#4CAF50'
          },
          textStyle: {
            color: '#666'
          },
          borderColor: "#e3e3e3",
          fillerColor: 'rgb(97, 105, 224)',
          borderRadius: 16,
          zoomLock: true,
          brushSelect: false, // 是否开启刷选功能，可以理解为拖拽区域的宽度
          backgroundColor: '#e3e3e3',//两边未选中的滑动条区域的颜色
          showDataShadow: false,//是否显示数据阴影 默认auto
          showDetail: false,//即拖拽时候是否显示详细数值信息 默认true
          filterMode: 'filter',
          zlevel: -10,
          // 自动滚动到最后
          startValue: Math.max(0, this.xAxisData.length - 15),
          endValue: this.xAxisData.length - 1
        }, {
          type: 'inside',
          xAxisIndex: [0],
          zoomOnMouseWheel: false, //滚轮不触发缩放
          moveOnMouseMove: true,   //鼠标移动触发平移
          moveOnMouseWheel: true,  //鼠标滚轮触发平移
        }] : [],
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.xAxisData,
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#666',
            fontSize: 12,
            // 当数据较多时，自动旋转标签避免重叠
            rotate: this.xAxisData.length > 10 ? 45 : 0,
            interval: 0 // 显示所有标签
          }
        },
        yAxis: {
          type: 'value',
          axisLine: { lineStyle: { color: "#e2e8ff" } }, // 轴线颜色
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#666',
            fontSize: 12
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0',
              type: 'dashed'
            }
          }
        },
        series: this.seriesData.map(item => ({
          name: item.name,
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            width: 3,
            color: item.color
          },
          itemStyle: {
            color: item.color,
            borderColor: '#fff',
            borderWidth: 2
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: this.hexToRgba(item.color, 0.3) },
                { offset: 1, color: this.hexToRgba(item.color, 0.05) }
              ]
            }
          },
          data: item.data
        }))
      };

      // 强制完整重渲染，避免旧配置残留
      this.chartInstance.clear();
      this.chartInstance.setOption(option, { notMerge: true, lazyUpdate: false });
    },

    hexToRgba(hex, alpha) {
      const r = parseInt(hex.slice(1, 3), 16);
      const g = parseInt(hex.slice(3, 5), 16);
      const b = parseInt(hex.slice(5, 7), 16);
      return `rgba(${r}, ${g}, ${b}, ${alpha})`;
    },

    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.line-chart-container {
  .chart-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 15px;
    color: #333;
    text-align: center;
  }
}
</style>
